package com.example.gui;

import com.example.dao.AdminDAO;
import com.example.model.UserInfo;
import com.example.util.UserTableModel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.List;


// 客户管理面板
public class CustomerManagementPanel extends JPanel {


    static AdminDAO adminDAO = new AdminDAO();

    UserTableModel tableModel;
    JTable userTable;
    List<UserInfo> userData;


    public CustomerManagementPanel() {

        userData = fetchUserData();
        tableModel = new UserTableModel(userData);
        userTable = new JTable(tableModel);

        // 设置表格外观
        userTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        userTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));
        userTable.setRowHeight(30);
        userTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);


        setLayout(new BorderLayout());
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 标题
        JLabel titleLabel = new JLabel("客户信息管理", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        add(titleLabel, BorderLayout.NORTH);


        add(new JScrollPane(userTable), BorderLayout.CENTER);

        // 底部按钮
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));

        JButton addButton = createStyledButton("添加用户", Color.decode("#4CAF50"));
        JButton editButton = createStyledButton("修改用户", Color.decode("#2196F3"));
        JButton deleteButton = createStyledButton("删除用户", Color.decode("#F44336"));
        JButton refreshButton = createStyledButton("刷新数据", Color.decode("#FF9800"));

        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(refreshButton);

        // 添加按钮事件处理
            addButton.addActionListener(this::addUser);
            editButton.addActionListener(this::editUser);
            deleteButton.addActionListener(this::deleteUser);
            refreshButton.addActionListener(e -> refreshData());

        add(buttonPanel, BorderLayout.SOUTH);
    }


    public static JButton createStyledButton(String text, Color bgColor) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.BOLD, 14));
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setPreferredSize(new Dimension(120, 40));
        return button;
    }

    private List<UserInfo> fetchUserData() {
        List<UserInfo> data = adminDAO.getUserInfo();
        return data;
    }

    private void addUser(ActionEvent e) {
        // 创建添加用户对话框
        JPanel formPanel = new JPanel(new GridLayout(5, 2, 10, 10));

        JTextField nameField = new JTextField();
        JTextField pidField = new JTextField();
        JTextField phoneField = new JTextField();
        JTextField addressField = new JTextField();

        formPanel.add(new JLabel("姓名:"));
        formPanel.add(nameField);
        formPanel.add(new JLabel("身份证号:"));
        formPanel.add(pidField);
        formPanel.add(new JLabel("电话:"));
        formPanel.add(phoneField);
        formPanel.add(new JLabel("地址:"));
        formPanel.add(addressField);

        int result = JOptionPane.showConfirmDialog(
                this,
                formPanel,
                "添加新用户",
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.PLAIN_MESSAGE
        );

        if (result == JOptionPane.OK_OPTION) {
            try {
                int id = getNextUserId();
                String name = nameField.getText().trim();
                String pid = pidField.getText().trim();
                String phone = phoneField.getText().trim();
                String address = addressField.getText().trim();

                if (!name.isEmpty() && !phone.isEmpty()) {
                    UserInfo newUser = new UserInfo(id, name,  pid, phone, address);

                    // 更新数据库
                    if(!adminDAO.addNewCustomer(newUser)){
                        JOptionPane.showMessageDialog(this, "用户信息有误!", "出错", JOptionPane.INFORMATION_MESSAGE);
                        return;
                    }

                    userData.add(newUser);
                    tableModel.fireTableDataChanged();
                    JOptionPane.showMessageDialog(this, "用户添加成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(this, "姓名和邮箱不能为空!", "输入错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "年龄必须为数字!", "输入错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void editUser(ActionEvent e) {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要修改的用户!", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        UserInfo user = userData.get(selectedRow);

        // 创建编辑用户对话框
        JPanel formPanel = new JPanel(new GridLayout(5, 2, 10, 10));

        JTextField idField = new JTextField(String.valueOf(user.getPid()));
        idField.setEditable(false);
        JTextField nameField = new JTextField(user.getCustomerName());
        JTextField ageField = new JTextField(String.valueOf(user.getPid()));
        JTextField emailField = new JTextField(user.getTelephone());
        JTextField departmentField = new JTextField(user.getAddress());

        formPanel.add(new JLabel("ID:"));
        formPanel.add(idField);
        formPanel.add(new JLabel("姓名:"));
        formPanel.add(nameField);
        formPanel.add(new JLabel("身份证号码:"));
        formPanel.add(ageField);
        formPanel.add(new JLabel("电话:"));
        formPanel.add(emailField);
        formPanel.add(new JLabel("地址:"));
        formPanel.add(departmentField);

        int result = JOptionPane.showConfirmDialog(
                this,
                formPanel,
                "编辑用户信息",
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.PLAIN_MESSAGE
        );

        if (result == JOptionPane.OK_OPTION) {
            try {
                String name = nameField.getText().trim();
                String pid = ageField.getText().trim();
                String phone = emailField.getText().trim();
                String address = departmentField.getText().trim();

                if (!name.isEmpty() && !phone.isEmpty()) {
                    user.setCustomerName(name);
                    user.setPid(pid);
                    user.setTelephone(phone);
                    user.setAddress(address);

                    if(!adminDAO.updateCustomerInfo(user)){
                        JOptionPane.showMessageDialog(this, "用户信息更新失败，请重试", "出错", JOptionPane.INFORMATION_MESSAGE);
                        return;
                    }


                    tableModel.fireTableRowsUpdated(selectedRow, selectedRow);
                    JOptionPane.showMessageDialog(this, "用户信息已更新!", "成功", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(this, "姓名和电话不能为空!", "输入错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "信息有误！", "输入错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void deleteUser(ActionEvent e) {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要删除的用户!", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        UserInfo user = userData.get(selectedRow);
        int confirm = JOptionPane.showConfirmDialog(
                this,
                "确定要删除用户 " + user.getCustomerName() + " (ID: " + user.getPid() + ") 吗?",
                "确认删除",
                JOptionPane.YES_NO_OPTION
        );

        if (confirm == JOptionPane.YES_OPTION) {

            if(!adminDAO.deleteUserInfo(user.getCustomerId())){
                JOptionPane.showMessageDialog(this, "用户删除失败!", "错误", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            userData.remove(selectedRow);
            tableModel.fireTableRowsDeleted(selectedRow, selectedRow);
            JOptionPane.showMessageDialog(this, "用户已删除!", "成功", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    private void refreshData() {
        userData.clear();
        userData.addAll(fetchUserData());
        tableModel.fireTableDataChanged();
        JOptionPane.showMessageDialog(this, "数据已刷新!", "成功", JOptionPane.INFORMATION_MESSAGE);
    }


    private int getNextUserId() {
        int maxId = 0;
        for (UserInfo user : userData) {
            if (user.getCustomerId() > maxId) {
                maxId = user.getCustomerId();
            }
        }
        return maxId + 1;
    }



}
